/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.coders;

import java.nio.ByteBuffer;

import org.latestbit.smartobjects.exceptions.InvalidPacketReceivedException;
import org.latestbit.smartobjects.io.ResizableByteBuffer;
import org.latestbit.smartobjects.network.IPacketFormer;

public class StdPacketFormer implements IPacketFormer {
	private static final int INITIAL_CAPACITY = 65535;		  // intial capacity
	private static final int MAX_CAPACITY = 1024 * 1024 * 16; // 16 Mb
	private static final int INCREMENT_CAPACITY_STEP = 65535; // 65 Kb step
	public static final int MAX_PACKET_SIZE = MAX_CAPACITY;
	
	private ResizableByteBuffer[] packetsBuffer = new ResizableByteBuffer[] { 
			new ResizableByteBuffer(false, INITIAL_CAPACITY, MAX_CAPACITY, INCREMENT_CAPACITY_STEP),
			new ResizableByteBuffer(false, INITIAL_CAPACITY, MAX_CAPACITY, INCREMENT_CAPACITY_STEP)
	};
	
	private int currentIdx = 0;
	private boolean headerIsReaded = false;
	private int currentLen = 0;
	private boolean needToClear = false;
	
	private int currentBufferLen = 0;
	private int currentReadPosition = 0;
	
	@Override
	public void onReceiveRawPacket ( ByteBuffer buffer ) {
		if( currentBufferLen !=0 ) {
			// Save state of buffer
			ByteBuffer currentBuffer = packetsBuffer[currentIdx].getBuffer();
			currentBuffer.position ( currentReadPosition );
			currentBuffer.limit ( currentReadPosition + currentBufferLen );
			
			// Copy second (next) packet data to another buffer
			currentIdx =  currentIdx == 0 ? 1:0;
			packetsBuffer[currentIdx].getBuffer().clear();
			packetsBuffer[currentIdx].put(currentBuffer);
			currentBuffer.clear();
		}
		packetsBuffer[currentIdx].put(buffer);
		currentBufferLen = packetsBuffer[currentIdx].getBuffer().position(); 
		currentReadPosition = 0;
	}
	
	@Override
	public ByteBuffer getReadyPacket() throws InvalidPacketReceivedException {
		ByteBuffer currentBuffer = packetsBuffer[currentIdx].getBuffer();
		if(needToClear) {
			currentBuffer.clear();
			needToClear = false;
			currentLen = 0;
			currentReadPosition = 0;
			currentBufferLen = 0;
			headerIsReaded = false;
			return null;
		}
		else {
			currentBuffer.limit(currentBuffer.capacity());
		}
		
		if(currentBufferLen > StdNetworkCommand.HEADER_SIZE && !headerIsReaded) {
			currentLen = currentBuffer.getInt(currentReadPosition + StdNetworkCommand.COMMAND_SIZE_POSITION);
			if(currentLen + StdNetworkCommand.HEADER_SIZE > MAX_PACKET_SIZE) {
				throw new InvalidPacketReceivedException("The received packet is too big: "+currentLen);
			}
			/* if(currentLen > 77) {
				System.err.println("Get len "+currentLen+" from "+ (currentReadPosition + StdNetworkCommand.COMMAND_SIZE_POSITION));
				System.err.println("BUFFER="+currentBuffer);
				byte[] tempBuff = new byte[500];
				currentBuffer.get(tempBuff);
				System.err.println("BUFFER="+ByteTools.byteArrayToHexString(tempBuff));
				System.exit(-1);
			} */
			headerIsReaded = true;
		}		
		
		if(headerIsReaded){
			int packetSize = currentLen + StdNetworkCommand.HEADER_SIZE; 
			if( currentBufferLen >= packetSize ) {
				if(currentBufferLen == packetSize) {
					// Packet in the current buffer is alone and the buffer need to clear
					// after proceed					
					needToClear  = true;
				}
				currentBuffer.position( currentReadPosition );
				currentBuffer.limit ( currentReadPosition + packetSize );
				headerIsReaded = false;
				currentReadPosition+=packetSize;
				currentBufferLen-=packetSize;
				return currentBuffer;
			}
			else
				return null;
		}
		else
			return null;
	}

	@Override
	public void reset() {
		packetsBuffer[0].getBuffer().clear();
		packetsBuffer[1].getBuffer().clear();
		needToClear = false;
		currentLen = 0;
		currentReadPosition = 0;
		currentBufferLen = 0;
		headerIsReaded = false;
	}
}
